import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/ui/custom/LoadingDialog.dart';
import 'package:flutter_juwo/ui/custom/city_picker.dart';
import 'package:flutter_juwo/ui/custom/judje_dialog.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/inforPages/initAccount/user_tags.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/representation/model/up_image_entity.dart';
import 'package:flutter_juwo/ui/pages/photoHero/PhotoHero.dart';
import 'package:flutter_juwo/ui/pages/photoHero/PhotoHeroNet.dart';
import 'package:flutter_juwo/ui/pages/photoHero/showBigImage.dart';
import 'package:flutter_juwo/ui/pages/photoHero/showBigImageNet.dart';
import 'package:flutter_juwo/ui/res/strings.dart';
import 'package:flutter_juwo/ui/utils/image_compress_utils.dart';
import 'package:flutter_juwo/ui/utils/select_pic.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import 'model/plat_infor_entity.dart';
import 'model/check_username_entity.dart';

/**
 * 添加电商平台账号
 * */
class InitPlatAccount extends StatefulWidget {
  String platId;
  String id;

  InitPlatAccount(this.platId, this.id);

  @override
  _InitPlatAccountState createState() => _InitPlatAccountState();
}

class _InitPlatAccountState extends State<InitPlatAccount> {
  MyPageState ps = MyPageState.LOADING;
  PlatInforEntity entity;

  //var textEditingControllers = <TextEditingController>[];
  File imageFile;
  String imgUrl;
  String userOldName;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    this.initData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: UiUtils.appBar(context, "添加电商账号"),
      body: this.getBody(),
    );
  }

  void initData() {
    FormData formData =
        FormData.from({"platId": widget.platId, "id": widget.id});
    DioManager.getInstance().get(Api.USER_GETPLATACCOUNTARGS, formData, (json) {
      print("获取平台需要信息：$json");

      entity = PlatInforEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBackWithParams(context, false);
        return;
      }

      if (entity.code != 200) {
        ToastUtil.showShortErrToast(entity.message);
        NavigatorUtils.goBackWithParams(context, false);
        return;
      }

      if (entity.code == 200) {
        for (int i = 0; i < entity.data.parms.length; i++) {
          if (entity.data.parms[i].lableName == "账户名") {
            userOldName = entity.data.parms[i].value;
          }
        }

        ps = MyPageState.HAVE_DATA;
        setState(() {});
        return;
      }
    }, (err) {
      ToastUtil.showShortErrToast(err);
      NavigatorUtils.goBackWithParams(context, false);
    });
  }

  ///获取ui
  getBody() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.HAVE_DATA) {
      return getContent();
    }
    return Container();
  }

  getContent() {
    List<Widget> widgets = [];

    ///电商类别
    widgets.add(getPlatType());

    for (int i = 0; i < entity.data.parms.length; i++) {
      if (entity.data.parms[i].status == "2") {
        continue;
      }

      if (entity.data.parms[i].type == "1") {
        TextEditingController controller =
            new TextEditingController(text: entity.data.parms[i].value);
        controller.addListener(() {
          entity.data.parms[i].value = controller.text;
        });

        ///在 收货人 上面加提示语句
        if (entity.data.parms[i].lableName == "收货人") {
          widgets.add(getTips(entity.data.platInfo.name));
        }

        widgets.add(getRowType1(entity.data.parms[i].lableName,
            "请输入${entity.data.parms[i].lableName}", controller));
      }

      if (entity.data.parms[i].type == "2") {
        bool isLocation = true;

        if (entity.data.parms[i].valueList == null ||
            entity.data.parms[i].valueList.length == 0 ||
            entity.data.parms[i].valueList[0].children == null ||
            entity.data.parms[i].valueList[0].children.length == 0) {
          isLocation = false;
        }
        widgets.add(getRowType2(
            entity.data.parms[i].lableName,
            entity.data.parms[i].value,
            isLocation,
            entity.data.parms[i].valueList,
            i));
      }

      if (entity.data.parms[i].type == "3") {
        imgUrl = entity.data.parms[i].value;
        widgets.add(getRowType3(entity.data.parms[i].lableName, i));
      }
    }

    return Container(
      child: Column(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: ListView(
              children: widgets,
            ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(30),
                ScreenUtil().setWidth(30),
                ScreenUtil().setWidth(30),
                ScreenUtil().setWidth(30)),
            child: UiUtils.bottomBotton("下一步", () async {
              ///TODO 1.验证输入是否正确
              UiUtils.showMyDialog(context, text: "验证数据中...");
              bool isok = await checkParm();
              if (isok) {
                StringBuffer sb = StringBuffer();
                sb.write("[");

                ///TODO 2.组装json
                for (int i = 0; i <= entity.data.parms.length - 1; i++) {
                  if (entity.data.parms[i].status == "2") {
                    continue;
                  }

                  sb.write("{\"lid\":\"");
                  sb.write(entity.data.parms[i].lid);
                  sb.write("\",");

                  sb.write("\"lable_id\":\"");
                  sb.write(entity.data.parms[i].lableId);
                  sb.write("\",");

                  sb.write("\"lable_name\":\"");
                  sb.write(entity.data.parms[i].lableName);
                  sb.write("\",");

                  sb.write("\"value\":\"");
                  sb.write(entity.data.parms[i].value);
                  sb.write("\",");

                  sb.write("\"valueId\":\"");
                  if (entity.data.parms[i].type == "2") {
                    sb.write(getValueId(entity.data.parms[i].valueList,
                        entity.data.parms[i].value));
                  } else {
                    sb.write("");
                  }
                  sb.write("\",");

                  sb.write("\"type\":\"");
                  sb.write(entity.data.parms[i].type);
                  sb.write("\"}");

                  if (i != entity.data.parms.length - 1) {
                    sb.write(",");
                  }
                }
                sb.write("]");
                print("输入的：${sb.toString()}");

                ///TODO 3.跳转到选择标签页面
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => UserTagsPage(
                          sb.toString(), widget.platId, widget.id)),
                );

                ///NavigatorUtils.push(context, "${Routes.userTags}?arr=${sb.toString()}");
              }
            }),
          )
        ],
      ),
    );
  }

  ///样式三 右侧用户选择图片
  getRowType3(String name, int i) {
    return this.myItemContainer(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        getLeft(name),
        getPic(i),
      ],
    ));
  }

  ///样式二 右侧用户选择文字
  getRowType2(String name, String value, bool isLocation,
      List<PlatInforDataParmsValuelist> valueList, int i) {
    return this.myItemContainer(
        child: Row(
      children: <Widget>[
        getLeft(name),
        Expanded(
          flex: 1,
          child: InkWell(
            onTap: () {
              if (isLocation) {
                ///地址联动
                _showSelectArea(valueList, i);
              } else {
                ///弹窗
                _showSelectAccountTypeDialog(valueList, i, name);
              }
            },
            child: Text(
              value == "" ? "请选择$name" : value,
              style: TextStyles.custom(
                  30,
                  value == "" ? Colours.appC3 : Colours.appC2,
                  Font.PingFangMedium),
              textAlign: TextAlign.end,
            ),
          ),
        )
      ],
    ));
  }

  ///样式一 右侧用户输入
  getRowType1(String name, String tips, TextEditingController controller) {
    return this.myItemContainer(
        child: Row(
      children: <Widget>[
        Expanded(
          flex: 1,
          child: getLeft(name),
        ),
        Expanded(
          flex: 2,
          child: UiUtils.myTextField1(context, controller,
              hintText: tips, maxLines: 1),
        )
      ],
    ));
  }

  _showSelectAccountTypeDialog(
      List<PlatInforDataParmsValuelist> valueList, int j, String name) {
    List<Widget> widgets = [];
    widgets.add(
      Container(
        height: ScreenUtil().setWidth(78),
        child: Text(
          name,
          style:
              TextStyles.custom(30, Colours.appC1, Font.PingFangBlod),
        ),
      ),
    );
    for (int i = 0; i < valueList.length; i++) {
      widgets.add(UiUtils.divider());
      widgets.add(InkWell(
        onTap: () {
          entity.data.parms[j].value = valueList[i].text;
          entity.data.parms[j].valueId = valueList[i].id;
          setState(() {});
          NavigatorUtils.goBack(context);
        },
        child: Container(
          height: ScreenUtil().setWidth(90),
          alignment: Alignment.center,
          child: Text(
            "${valueList[i].text}",
            style: TextStyles.custom(
                28, Colours.appC16, Font.PingFangMedium),
          ),
        ),
      ));
    }

    showElasticDialog(
        context: context,
        builder: (BuildContext context) {
          return Material(
            type: MaterialType.transparency,
            child: Center(
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.0),
                ),
                width: ScreenUtil().setWidth(540),
                height: ScreenUtil()
                    .setWidth(48 + 78 + (90 + 1.0) * valueList.length),
                padding: EdgeInsets.only(top: ScreenUtil().setWidth(48)),
                child: Theme(
                  data: ThemeData(
                    buttonTheme: ButtonThemeData(
                      minWidth: double.infinity,
                    ),
                    textTheme: TextTheme(
                        button: TextStyle(
                      fontSize: Dimens.font_sp14,
                    )),
                  ),
                  child: Column(
                    children: widgets,
                  ),
                ),
              ),
            ),
          );
        });
  }

  ///电商类别
  Widget getPlatType() {
    return this.myItemContainer(
        child: Row(
      children: <Widget>[
        this.getLeft("电商类别"),
        Expanded(
          flex: 1,
          child: Container(
            margin: EdgeInsets.only(right: ScreenUtil().setWidth(20)),
            alignment: Alignment.centerRight,
            child: UiUtils.cachedNetworkImage(
                30, 30, entity.data.platInfo.picture),
          ),
        ),
        this.getRight(entity.data.platInfo.name)
      ],
    ));
  }

  ///通用item外层的样式
  myItemContainer({Widget child, double marginTop = 2}) {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(marginTop)),
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(30),
          ScreenUtil().setWidth(20)),
      color: Colors.white,
      child: child,
    );
  }

  ///通用的左侧文本样式
  getLeft(String txt) {
    return Text(
      "$txt",
      style: TextStyles.custom(30, Colours.appC1, Font.PingFangMedium),
    );
  }

  ///通用的右侧文本样式
  getRight(String txt) {
    return Text(
      "$txt",
      style: TextStyles.custom(28, Colours.appC2, Font.PingFangMedium),
    );
  }

  @override
  void dispose() {
    // TODO: 释放资源
    super.dispose();
  }

  void _showSelectArea(List<PlatInforDataParmsValuelist> valueList, int i) {
    CityPicker.showCityPicker(
      context,
      valueList,
      selectProvince: (province) {
        print(province);
        entity.data.parms[i].value = province["name"];
      },
      selectCity: (city) {
        entity.data.parms[i].value =
            "${entity.data.parms[i].value}-${city["name"]}";
        setState(() {});
        print(city);
      },
    );
  }

  Widget getTips(String name) {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
      padding: EdgeInsets.all(ScreenUtil().setWidth(30)),
      child: Text(
        "请务必与该$name账号收货地址一致，否则可能导致商家封店或降权，或拍手账号被冻结。",
        style: TextStyles.custom(
            30, Colours.appC16, Font.PingFangRegular),
      ),
    );
  }

  Widget getPic(int i) {
    Widget child;
    if (null != imageFile) {
      child = getPicContainer(imageFile, i);
    } else if (imgUrl.isNotEmpty) {
      child = getPicContainer2(imgUrl, i);
    } else {
      child = getImageAdd(i);
    }

    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(30)),
      child: child,
    );
  }

  getImageAdd(int i) {
    return InkWell(
      onTap: () {
        getImage(i);
      },
      child: SelectPic.selectPic,
    );
  }

  Future getImage(int i) async {
    /*   var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (image == null) {
      return;
    }
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return LoadingDialog(
            text: "上传中",
          );
        });
    _upLoadImage(image,i); //上传图片*/

    Map<PermissionGroup, PermissionStatus> permissions =
        await PermissionHandler().requestPermissions([PermissionGroup.storage]);

    // 申请结果  权限检测
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.storage);

    if (permission == PermissionStatus.granted) {
      //权限申请通过
      var image = await ImagePicker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return LoadingDialog(
                text: "上传中",
              );
            });
        _upLoadImage(image, i); //上传图片
      }
    } else {
      showElasticDialog(
          context: context,
          builder: (BuildContext context) {
            return JudjeDialog(
              title: "没有访问存储权限",
              value: Strings.NO_PERMISSION_MSG,
              onPressed: () async {
                NavigatorUtils.goBack(context);
                //权限申请被拒绝！
                bool isOpened = await PermissionHandler().openAppSettings();
                if (isOpened) {
                  print("打开设置页面");
                } else {
                  ToastUtil.showShortToast("");
                }
              },
            );
          });
    }
  }

  Widget getPicContainer(File url, int i) {
    return Container(
        child: Stack(
      children: <Widget>[
        PhotoHero(
            photo: url,
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => ShowBigImagePage(url)),
              );
            },
            width: ScreenUtil().setWidth(180)),
        Positioned(
            left: 40.0,
            right: 0,
            top: 0.0,
            child: InkWell(
              onTap: () {
                setState(() {
                  imageFile = null;
                  imgUrl = "";
                  entity.data.parms[i].value = "";
                });
              },
              child: Image.asset(
                Utils.getImgPath('icon_delete01'),
                width: 20.0,
                height: 20.0,
              ),
            ))
      ],
    ));
  }

  Widget getPicContainer2(String url, int i) {
    return Container(
        child: Stack(
      children: <Widget>[
        PhotoHeroNet(
            photo: url,
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => ShowBigImagePageNet(url)),
              );
            },
            width: ScreenUtil().setWidth(180)),
        Positioned(
            left: 40.0,
            right: 0,
            top: 0.0,
            child: InkWell(
              onTap: () {
                setState(() {
                  imageFile = null;
                  imgUrl = "";
                  entity.data.parms[i].value = "";
                });
              },
              child: Image.asset(
                Utils.getImgPath('icon_delete01'),
                width: 20.0,
                height: 20.0,
              ),
            ))
      ],
    ));
  }

  _upLoadImage(File image, int i) async {
    File result = await CompressImage.testCompressAndGetFile(image, image.path);
    String path = result.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData = new FormData.from(
        {"pic": new UploadFileInfo(new File(path), name), "dir": "appstore"});
    DioManager.getInstance().post(Api.USER_UPLODIMG, formData, (json) {
      UpImageEntity upImageEntity = UpImageEntity.fromJson(json);

      ///上传失败
      if (upImageEntity == null) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        return;
      }
      if (upImageEntity.status != "200") {
        ToastUtil.showShortErrToast(upImageEntity.message);
        return;
      }

      ///上传 成功 显示图片
      if (upImageEntity.status == "200") {
        imageFile = image;
        imgUrl = upImageEntity.data;
        entity.data.parms[i].value = imgUrl;
        setState(() {});
      }
      NavigatorUtils.goBack(context);

      print("上传成功：$json");
    }, (err) {
      NavigatorUtils.goBack(context);
      print("上传失败：$err");
    });
  }

  ///验证各种数据
  Future<bool> checkParm() async {
    for (int i = 0; i < entity.data.parms.length; i++) {
      PlatInforDataParm parm = entity.data.parms[i];

      if (parm.status == "2") {
        continue;
      }

      ///账户名需要数据库比对
      if (parm.lableName == "账户名") {
        if (parm.value.isEmpty) {
          ToastUtil.showShortErrToast("请输入账户名！");
          UiUtils.dismissMyDialog(context);
          return false;
        }

        if (userOldName == parm.value) {
          continue;
        }

        ///判断用户名是否合法
        bool isOK = await checkUserName(parm.value);
        if (!isOK) {
          UiUtils.dismissMyDialog(context);
          return false;
        }
        continue;
      }

      if (parm.type == "1") {
        if (parm.value.isEmpty) {
          ToastUtil.showShortErrToast("请输入${parm.lableName}！");
          UiUtils.dismissMyDialog(context);
          return false;
        }
      }
      if (parm.type == "2") {
        if (parm.value.isEmpty) {
          ToastUtil.showShortErrToast("请选择${parm.lableName}！");
          UiUtils.dismissMyDialog(context);
          return false;
        }
      }

      if (parm.lableName == "个人中心截图") {
        parm.value = imgUrl;
        if (parm.value.isEmpty) {
          ToastUtil.showShortErrToast("请上传个人中心截图！");
          UiUtils.dismissMyDialog(context);
          return false;
        }
      }
    }
    UiUtils.dismissMyDialog(context);

    return true;
  }

  Future<bool> checkUserName(String value) async {
    FormData formData =
        FormData.from({"platId": "${widget.platId}", "account": value});

    try {
      Response data = await DioManager.getInstance()
          .dio
          .post(Api.USER_EXAMACCOUNT, data: formData);

      var strJson = json.decode(data.data);
      print("==================1.${strJson.toString()}=======================");

      CheckUsernameEntity checkUsernameEntity =
          CheckUsernameEntity.fromJson(strJson);
      if (null == checkUsernameEntity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        return false;
      }
      if (checkUsernameEntity.code != 200) {
        ToastUtil.showShortErrToast("账号不通过：${checkUsernameEntity.message}");
        return false;
      }
      return true;
    } on DioError catch (error) {
      // 请求错误处理
      ToastUtil.showShortErrToast("账号不通过：${Api.ERR_NOTHING}");
      return false;
    }
  }

  String getValueId(List<PlatInforDataParmsValuelist> valueList, String value) {
    for (int i = 0; i < valueList.length; i++) {
      if (value == valueList[i].text) {
        return valueList[i].id;
      }
    }
    return "-1";
  }
}
